'use client'

import { useState } from 'react'
import { Badge, Button, Card, Empty, List, Pagination, Space, Tag, Tabs, message } from 'antd'
import { BellOutlined, CheckOutlined, DeleteOutlined } from '@ant-design/icons'
import useSWR from 'swr'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import 'dayjs/locale/zh-cn'

import {
  fetchNotifications,
  markNotificationAsRead,
  markAllNotificationsAsRead,
  deleteNotification
} from './api'
import type { Notification } from './types'
import styles from './page.module.scss'

dayjs.extend(relativeTime)
dayjs.locale('zh-cn')

const { TabPane } = Tabs

export default function NotificationPage() {
  const [page, setPage] = useState(1)
  const [activeTab, setActiveTab] = useState('all') // 'all' | 'unread'
  const perPage = 20

  // 使用 SWR 获取数据
  const { data, error, isLoading, mutate } = useSWR(
    ['notifications', page, activeTab],
    () => fetchNotifications({
      page,
      per_page: perPage,
      unread_only: activeTab === 'unread',
    })
  )

  // 标记单个通知为已读
  const handleMarkAsRead = async (notificationId: number) => {
    try {
      await markNotificationAsRead(notificationId)
      message.success('已标记为已读')
      mutate() // 重新获取数据
    } catch (error) {
      message.error('操作失败')
    }
  }

  // 标记所有为已读
  const handleMarkAllAsRead = async () => {
    try {
      await markAllNotificationsAsRead()
      message.success('全部标记为已读')
      mutate()
    } catch (error) {
      message.error('操作失败')
    }
  }

  // 删除通知
  const handleDelete = async (notificationId: number) => {
    try {
      await deleteNotification(notificationId)
      message.success('删除成功')
      mutate()
    } catch (error) {
      message.error('删除失败')
    }
  }

  // 通知类型颜色映射
  const typeColorMap = {
    info: 'blue',
    success: 'green',
    warning: 'orange',
    error: 'red',
  }

  // 渲染通知项
  const renderNotificationItem = (item: Notification) => (
    <List.Item
      key={item.id}
      className={`${styles.notificationItem} ${!item.is_read ? styles.unread : ''}`}
      actions={[
        !item.is_read && (
          <Button
            type="link"
            size="small"
            icon={<CheckOutlined />}
            onClick={() => handleMarkAsRead(item.id)}
          >
            标记已读
          </Button>
        ),
        <Button
          type="link"
          size="small"
          danger
          icon={<DeleteOutlined />}
          onClick={() => handleDelete(item.id)}
        >
          删除
        </Button>,
      ].filter(Boolean)}
    >
      <List.Item.Meta
        avatar={
          !item.is_read && <Badge status="processing" />
        }
        title={
          <Space>
            <span className={styles.title}>{item.title}</span>
            <Tag color={typeColorMap[item.type]}>{item.type}</Tag>
          </Space>
        }
        description={
          <div>
            <div className={styles.content}>{item.content}</div>
            <div className={styles.time}>
              {dayjs(item.created_at).fromNow()}
            </div>
          </div>
        }
      />
    </List.Item>
  )

  return (
    <div className={styles.notificationPage}>
      <Card
        title={
          <Space>
            <BellOutlined />
            <span>通知中心</span>
            {data && data.unread_count > 0 && (
              <Badge count={data.unread_count} />
            )}
          </Space>
        }
        extra={
          <Button
            type="primary"
            onClick={handleMarkAllAsRead}
            disabled={!data || data.unread_count === 0}
          >
            全部标记为已读
          </Button>
        }
      >
        <Tabs
          activeKey={activeTab}
          onChange={(key) => {
            setActiveTab(key)
            setPage(1)
          }}
        >
          <TabPane tab="全部通知" key="all" />
          <TabPane
            tab={
              <Badge count={data?.unread_count} offset={[10, 0]}>
                未读通知
              </Badge>
            }
            key="unread"
          />
        </Tabs>

        {isLoading && <div className={styles.loading}>加载中...</div>}

        {error && (
          <Empty
            description="加载失败，请稍后重试"
            image={Empty.PRESENTED_IMAGE_SIMPLE}
          />
        )}

        {!isLoading && !error && data && (
          <>
            {data.notifications.length === 0 ? (
              <Empty
                description={activeTab === 'unread' ? '暂无未读通知' : '暂无通知'}
                image={Empty.PRESENTED_IMAGE_SIMPLE}
              />
            ) : (
              <>
                <List
                  dataSource={data.notifications}
                  renderItem={renderNotificationItem}
                  split
                />

                {data.total > perPage && (
                  <div className={styles.pagination}>
                    <Pagination
                      current={page}
                      pageSize={perPage}
                      total={data.total}
                      onChange={setPage}
                      showSizeChanger={false}
                      showTotal={(total) => `共 ${total} 条`}
                    />
                  </div>
                )}
              </>
            )}
          </>
        )}
      </Card>
    </div>
  )
}
